package ar.edu.unicen.exa.isistan.archassis.view.dialogs.sourcepanel;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import ar.edu.unicen.exa.isistan.archassis.source.FileSourceStrategy;
import ar.edu.unicen.exa.isistan.archassis.source.ISourceStrategy;
import swing2swt.layout.BorderLayout;
import org.eclipse.swt.widgets.Group;

public class FolderSourceStrategyPanel extends AbstractSourceStrategyPanel {
	private Text text;
	
	public FolderSourceStrategyPanel(Composite parent) {
		super(parent);
		setLayout(new BorderLayout(0, 0));
		Group grpDirectorioDeCodigo = new Group(this, SWT.NONE);
		grpDirectorioDeCodigo.setText("Directorio de codigo fuente");
		grpDirectorioDeCodigo.setLayoutData(BorderLayout.NORTH);
		grpDirectorioDeCodigo.setLayout(new BorderLayout(0, 0));
		
		text = new Text(grpDirectorioDeCodigo, SWT.BORDER);
		
		Button btnNewButton = new Button(grpDirectorioDeCodigo, SWT.NONE);
		btnNewButton.setLayoutData(BorderLayout.EAST);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				selectFolder();
			}
		});
		btnNewButton.setText("Explorar");
		
		
		
	}
	
	private void selectFolder() {
		File folder = selectFolder(this.getShell(), text.getText());
		if (folder != null) {
			text.setText(folder.getAbsolutePath());
		}
	}
	
	private static File selectFolder(Shell shell, String filterPath) {
		DirectoryDialog dlg = new DirectoryDialog(shell);

        // Set the initial filter path according
        // to anything they've selected or typed in
        dlg.setFilterPath(filterPath);

        // Change the title bar text
        dlg.setText("SWT's DirectoryDialog");

        // Customizable message displayed in the dialog
        dlg.setMessage("Select a directory");

        // Calling open() will open and run the dialog.
        // It will return the selected directory, or
        // null if user cancels
        String dir = dlg.open();
        
        if (dir == null) {
        	return null;
        }
        File folder = new File(dir);
        if (folder.isDirectory()) {
        	return folder;
        }
        return null;
	}

	@Override
	public ISourceStrategy getSourceStrategy() {
		File folder = new File(text.getText());
        if (folder.isDirectory()) {
        	return new FileSourceStrategy(folder);
        }
        return null;
	}

}
